package cn.tonyandmoney.voicenotes.ui.activity

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import cn.tonyandmoney.voicenotes.R
import cn.tonyandmoney.voicenotes.greendao.gen.NoteRecordDao
import cn.tonyandmoney.voicenotes.greendao.gen.TRecordDao
import cn.tonyandmoney.voicenotes.greendao.utils.GreenDaoHelper
import cn.tonyandmoney.voicenotes.notes.entity.TNote
import cn.tonyandmoney.voicenotes.notes.entity.TRecord
import cn.tonyandmoney.voicenotes.notes.model.FileModel
import cn.tonyandmoney.voicenotes.notes.presenter.impl.SearchPresenter
import cn.tonyandmoney.voicenotes.ui.component.lineDivider
import cn.tonyandmoney.voicenotes.utils.DateUtils
import cn.tonyandmoney.voicenotes.wav.ui.AudioPlayerActivity
import com.afollestad.materialdialogs.MaterialDialog
import com.zlzsy.app.base.ui.BaseActivity
import com.zlzsy.app.base.ui.adapter.KAdapter
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.*
import org.jetbrains.anko.recyclerview.v7.recyclerView
import java.util.*

/**
 * 我的文件列表
 * 文件是没有分类的，按所绑定的笔记的中文拼音
 */
class MyFilesActivity : BaseActivity(), AnkoLogger, SearchPresenter.ISearchView {

    private val mModel = FileModel()
    private val mAdapter = KAdapter<TRecord>()

    private var materialDialog: MaterialDialog? = null


    override fun initView() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        verticalLayout {
            recyclerView {
                topPadding = dip(10)
                bottomPadding = dip(10)
                layoutManager = LinearLayoutManager(this@MyFilesActivity)
                mAdapter.bindToRecyclerView(this)
            }.lparams(matchParent, matchParent)
        }
        mAdapter.setItemView {
            verticalLayout {
                lparams(matchParent, wrapContent)
                backgroundResource = android.R.color.white
                relativeLayout {
                    padding = dip(10)
                    textView {
                        id = R.id.note_name
                        textSize = 16f
                    }.lparams(matchParent, wrapContent)
                    textView {
                        id = R.id.record_duration
                    }.lparams(wrapContent, wrapContent) {
                        alignParentEnd()
                    }
                    textView {
                        id = R.id.record_name
                    }.lparams(wrapContent, wrapContent) {
                        topMargin = dip(5)
                        bottomOf(R.id.note_name)
                    }
                }.lparams(matchParent, wrapContent)
                lineDivider()
            }
        }.setDataBind { holder, tRecord ->
            holder.setText(R.id.note_name, tRecord.content)
            holder.setText(R.id.record_name, tRecord.fileName)
            holder.setText(R.id.record_duration, DateUtils.formatter(Date(tRecord.duration), "mm:ss"))
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val entity = mAdapter.getItem(position) ?: return@setOnItemClickListener
            startActivity<AudioPlayerActivity>("id" to entity.id)
        }
        mAdapter.setOnItemLongClickListener { _, _, position ->
            val entity = mAdapter.getItem(position) ?: return@setOnItemLongClickListener false
            MaterialDialog.Builder(this)
                    .content("确定要删除该文件及其关联吗？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive { _, _ ->
                        deleteFile(entity)
                    }
                    .show()
            return@setOnItemLongClickListener true
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        loadData()
        SearchPresenter(this, this)
    }

    override fun confirm() {
        if (materialDialog == null) return
        val keywords = materialDialog!!.inputEditText?.text?.toString()
        cancel()
        onSearch(keywords ?: "")
    }

    override fun cancel() {
        materialDialog?.dismiss()
        materialDialog = null
    }

    override fun showSearch(keywords: String) {
        materialDialog = MaterialDialog.Builder(this)
                .title("搜索")
                .input("请输入关键词", keywords, true, { _, input ->
                    onSearch(input.toString())
                })
                .positiveText("确定")
                .negativeText("取消")
                .show()
    }


    private fun onSearch(keywords: String) {
        mAdapter.setNewData(mModel.searchBy(keywords))
    }

    /**
     * 删除文件及其关联
     */
    private fun deleteFile(record: TRecord) {
        showLoadingDialog("正在删除，请稍候...")
        Observable.create<Int> {
            mModel.delete(record)
            loadData()
            it.onNext(0);it.onComplete()
        }.subscribeOn(Schedulers.io())
                .subscribe()


    }

    override fun onResume() {
        super.onResume()
        showLoadingDialog()
        loadData()
    }

    private fun loadData() {
        mModel.list { list, errMsg ->
            if (TextUtils.isEmpty(errMsg)) {
                mAdapter.setNewData(list)
            } else {
                toast(errMsg!!)
            }
            hideLoadingDialog()
        }
    }


    private fun loadDataByNoteId(note: TNote) {
        val recordIds = GreenDaoHelper.session().noteRecordDao
                .queryBuilder()
                .where(NoteRecordDao.Properties.NoteId.eq(note.id))
                .list()
                .map { it.recordId }
        val list = GreenDaoHelper.session().tRecordDao
                .queryBuilder()
                .where(TRecordDao.Properties.Id.`in`(recordIds))
                .list()
        mAdapter.setNewData(list)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.files_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.action_search_by_type) {
            val notes = GreenDaoHelper.session().tNoteDao.loadAll()
            MaterialDialog.Builder(this)
                    .title("按笔记名称检索")
                    .items(notes.map { it.name })
                    .itemsCallback { dialog, _, position, _ ->
                        dialog.dismiss()
                        val entity = notes[position] ?: return@itemsCallback
                        loadDataByNoteId(entity)
                    }
                    .negativeText(R.string.cancel)
                    .show()
            return true
        } else if (item.itemId == R.id.action_search) {
            showSearch("")
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}